<template>
  <div style="padding: 10px;">
    <el-row >
      <el-col>
        <div style="display: flex;">
          <div>
            <el-form :model="list_params" ref="searchForm"  size="small" :inline="true">
              <el-form-item label="搜索" label-width="80px" prop="oddNumber">
                <el-input v-model="list_params.oddNumber" placeholder="单据编号/合同号/货柜号" ></el-input>
              </el-form-item>
              <el-form-item label="付款对象" prop="roleType"> 
                <el-select filterable  v-model="list_params.roleType" placeholder="付款对象" clearable :style="{width: '100%'}" @change="onSearchPaymentRoleChange" >
                  <el-option label="客户" value="4"></el-option>
                  <el-option label="资方" value="5"></el-option>
                </el-select>
              </el-form-item>
                <el-form-item label="交易人" prop="tradeUserId">
                  <el-select filterable   placeholder="请选择" :style="{width: '100%'}" v-model="list_params.tradeUserId">
                    <el-option v-if="list_params.roleType == 5" v-for="item in search_payment_roles" :label="item.name" :value="item.id"></el-option>
                    <el-option v-if="list_params.roleType == 4" v-for="item in search_payment_roles" :label="item.customerName	" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              <el-form-item label="归属单位" prop="ownershipCompanyId">
                <el-select v-model="list_params.ownershipCompanyId">
                  <el-option v-for="item in ownership_company_list" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
                <el-button  size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div style="flex: 1;"></div>
          <div>
            <!--                      <el-button>删除</el-button>-->
            <!--                      <el-button @click="handleEnable(0)" >禁用</el-button>-->
            <!--                      <el-button @click="handleEnable(1)" >启用</el-button>-->
<!--            <el-button @click="handleExport">导出</el-button>-->
            <!--                      <el-button>导入</el-button>-->
            <el-button type="primary" @click="addInfo" >新增</el-button>
          </div>
        </div>
      </el-col>
      <el-col>
        <div style="margin-top: 10px;">
          <el-table :data="list_data" @selection-change="handleSelectionChange"  :height="table_height" style="width: 100%;" >
            <el-table-column type="selection" width="50" align="center"  />
            <el-table-column label="单据编号" prop="oddNumber" width="180"></el-table-column>
            <el-table-column label="供货单" prop="containerNumber" width="180"></el-table-column>
            <el-table-column label="付款对象" prop="roleType" width="180">
              <template slot-scope="scope" >
                <dict-tag  :options="dict.type.role_type" :value="scope.row.roleType"></dict-tag>
              </template>
            </el-table-column>
            <el-table-column label="交易人" prop="tradeUserName" width="180"></el-table-column>
            <el-table-column label="申请人" prop="applyUserName" width="180"></el-table-column>
            <el-table-column label="申请日期" prop="applyDate" width="180"></el-table-column>
            <el-table-column label="业务归属单位" prop="ownershipCompanyName" width="180"></el-table-column>
            <el-table-column label="付款公司" prop="paymentCompanyName" width="180"></el-table-column>
            <el-table-column label="预付款金额" prop="totalPrepaymentAmt" width="180"></el-table-column>
            <el-table-column label="核销金额" prop="totalReceiptAmt" width="180"></el-table-column>
            <el-table-column label="未核销金额" prop="totalReceiptAmt" width="180"></el-table-column>
            <el-table-column label="已核销金额" prop="totalReceiptAmt" width="180"></el-table-column>
            <el-table-column label="核销状态" prop="writeOffStatus" width="180">
              <template slot-scope="scope" >
                <dict-tag  :options="dict.type.write_off_status" :value="scope.row.writeOffStatus"></dict-tag>
              </template>
            </el-table-column>
            <el-table-column label="单据状态" prop="handleStatus" width="180">
              <template slot-scope="scope" >
                <dict-tag  :options="dict.type.handle_status" :value="scope.row.handleStatus"></dict-tag>
              </template>
            </el-table-column>
            <el-table-column label="结算账户" prop="cargoOwnerName" width="180">
              <template slot-scope="scope" >

              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
            <el-table-column label="备注" prop="remark" width="180"></el-table-column>
            <el-table-column label="操作" prop="op" fixed="right">
              <template slot-scope="scope" >
                <el-button
                  size="mini"
                  type="text"
                  @click="showInfo(scope.row)"
                >查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <el-drawer :title="form_data.id?'编辑预付款单':'新增预付款单'" size="80%" :visible.sync="dialog_show">
      <el-form  ref="form" :model="form_data" :rules="formDataRules" size="small" :inline="true">
        <div>
          <div class="section">
            <el-row>
              <!--              <el-col :span="6" >-->
              <!--                <el-form-item label="申请人" prop="applyUserId">-->
              <!--                  <el-select filterable  placeholder="请选择" :style="{width: '100%'}">-->
              <!--                  </el-select>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="6" >
                <el-form-item label="申请日期" prop="applyDate">
                  <el-date-picker type="date" placeholder="选择日期" style="width: 100%;" value-format="yyyy-MM-dd" v-model="form_data.applyDate"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6" >
                <el-form-item label="付款对象" prop="roleType">
                  <el-select filterable  placeholder="请选择" v-model="form_data.roleType" :style="{width: '100%'}" @change="onPaymentRoleChange">
                    <el-option label="客户" value="4"></el-option>
                    <el-option label="资方" value="5"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" >
                <el-form-item label="交易人" prop="tradeUserId">
                  <el-select filterable   placeholder="请选择" :style="{width: '100%'}" v-model="form_data.tradeUserId" @change="getSupplyList">
                    <el-option v-if="form_data.roleType == 5" v-for="item in payment_roles" :label="item.name" :value="item.id"></el-option>
                    <el-option v-if="form_data.roleType == 4" v-for="item in payment_roles" :label="item.customerName	" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" >
                <el-form-item label="业务归属单位" prop="ownershipCompanyId">
                  <el-select filterable   placeholder="请选择" :style="{width: '100%'}" v-model="form_data.ownershipCompanyId">
                    <el-option v-for="item in ownership_company_list" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" >
                <el-form-item label="付款公司" prop="paymentCompanyId">
                  <el-select filterable   placeholder="请选择" :style="{width: '100%'}" v-model="form_data.paymentCompanyId">
                    <el-option v-for="item in receipt_company_list" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" >
                <el-form-item label="供货清单" prop="supplyListId" filterable >
                  <el-select filterable   placeholder="请选择" :style="{width: '100%'}" v-model="form_data.supplyListId">
                    <el-option v-for="item in supply_list" :label="item.contractNumber +' - '+item.containerNumber +' - '+item.cargoOwnerName" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="section">
            <div style="padding-bottom: 12px;">付款明细</div>
            <div>
              <el-table :data="fees" style="width: 100%" >
                <el-table-column prop="date" label="序号">
                  <template slot-scope="scope" >
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column prop="date" label="结算账户">
                  <template slot-scope="scope" >
                    <el-select filterable   style="width: 100%;" v-model="fees[scope.$index].accountId" placeholder="请选择" >
                      <el-option v-for="dict in dict.type.settlement_way" :key="dict.value" :label="dict.label"
                                 :value="dict.value"  ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <!--                <el-table-column prop="date" label="币种">-->
                <!--                  <template slot-scope="scope" >-->
                <!--                    <el-select filterable   style="width: 100%;" v-model="fees[scope.$index].currency" placeholder="请选择" >-->
                <!--                      <el-option v-for="dict in dict.type.currency" :key="dict.value" :label="dict.label"-->
                <!--                                 :value="dict.value"  ></el-option>-->
                <!--                    </el-select>-->
                <!--                  </template>-->
                <!--                </el-table-column>-->
                <el-table-column prop="date" label="预付金额">
                  <template slot-scope="scope" >
                    <el-input v-model="fees[scope.$index].amt" @blur="sumData"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="date" label="备注">
                  <template slot-scope="scope" >
                    <el-input v-model="fees[scope.$index].remark"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="date" label="操作">
                  <template slot-scope="scope" >
                    <el-button
                      size="mini"
                      v-if="scope.$index != 0"
                      type="text"
                      @click="delFee(scope.row)"
                    >删除</el-button>
                    <el-button
                      size="mini"
                      type="text"
                      @click="addFee(scope.row)"
                    >新增</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="section">
            <div>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form_data.remark" placeholder="请输入"></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="section" style="display: flex;justify-content: flex-end;position: sticky;bottom: 0px;">
            <el-button type="primary" @click="submitData">提交</el-button>
          </div>
        </div>
      </el-form>
    </el-drawer>
    <el-drawer
      title="预付款单详情"
      size="80%"
      :visible.sync="edit_dialog_show">
      <div>
        <div class="section">
          <el-row>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">单据编号</div>
              <div>{{ info.oddNumber }}</div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">交易人</div>
              <div>{{info.tradeUserName	}}</div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">状态</div>
              <div><dict-tag :options="dict.type.handle_status" :value="info.handleStatus" ></dict-tag></div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">核销状态</div>
              <div><dict-tag :options="dict.type.write_off_status" :value="info.writeOffStatus" ></dict-tag></div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">申请人</div>
              <div>{{info.applyUserName	}}</div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">申请日期</div>
              <div>{{info.applyDate}}</div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">业务归属单位</div>
              <div>{{info.ownershipCompanyName	}}</div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">付款公司</div>
              <div>{{info.paymentCompanyName }}</div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">创建时间</div>
              <div>{{info.createTime}}</div>
            </el-col>
            <el-col :span="4" class="section-item">
              <div class="section-item-title">供货单</div>
              <div>{{ info.containerNumber }}</div>
            </el-col>
          </el-row>
        </div>
        <div class="section">
          <div style="padding-bottom: 12px;">付款明细</div>
          <div>
            <el-table :data="info.xnfReceiptSettleAccountsList" show-summary :summary-method="getSummaries">
              <el-table-column label="序号" width="100">
                <template slot-scope="scope" >
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="结算账户" prop="accountId">
                <template slot-scope="scope" >
                  <dict-tag  :options="dict.type.settlement_way" :value="scope.row.accountId"></dict-tag>
                </template>
              </el-table-column>
              <el-table-column label="预收金额" prop="amt"></el-table-column>
              <el-table-column label="备注" prop="remark" ></el-table-column>
            </el-table>
          </div>
          <div style="margin-top: 20px;">
            <div>备注：{{info.remark}}</div>
          </div>
        </div>

        <div class="section" style="display: flex;justify-content: flex-end;position: sticky;width: 100%;bottom: 0px;margin: 0px;">
          <el-button type="primary" @click="editInfo">编辑</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {list as supplyList} from "@/api/supply/order";
import {list as feeList} from "@/api/fee/fee";
import {list,add,detail,del,update} from "@/api/finance/pre_payment"
import {list as ownerList} from "@/api/base/owner"
import {list as capitalList} from "@/api/base/capital"
import {list as stallList} from "@/api/base/stall"
import {list as accountList} from "@/api/base/order_account"
import {list as customerList} from "@/api/base/customer"
import {list as receiptCompanyList} from "@/api/base/receipt_company"
import {list as ownershipCompanyList} from "@/api/base/ownership_company"
import {list as saleList} from "@/api/sell/sale_list"
import store from '@/store'

export default {
  name: 'receive',
  dicts:['settlement_way','currency','receipt_biz_type','receipt_purpose','handle_status',
    'write_off_status','role_type'],
  data(){
    return {
      table_height:window.innerHeight - 300,
      sale_list_params:{saleListNumber:''},
      order_dialog_show:false,
      dialog_show:false,
      edit_dialog_show:false,
      form_data:{},
      formDataRules:{
        applyDate:[
          {required:true,message:'请选择申请日期',trigger:'change'}
        ],
        roleType:[
          { required: true, message: '请选择付款对象', trigger: 'change' }
        ],
        tradeUserId:[
          { required: true, message: '请选择交易人', trigger: 'change' }
          ],
        ownershipCompanyId:[
          { required: true, message: '请选择业务归属单位', trigger: 'change' }
          ],
        paymentCompanyId:[
          { required: true, message: '请选择付款公司', trigger: 'change' }
          ],
        supplyListId:[
          { required: true, message: '请选择供货单', trigger: 'change' } ],
      },
      fees:[{ remark:'' }],
      list_params: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      owner_list:[],
      list_data:[],
      payment_roles:[],
      receipt_company_list:[],
      ownership_company_list:[],
      sale_list:[],
      sale_id_list:[],
      choose_order_list:[],
      orders:[],
      info:{},
      search_payment_roles:[],
      supply_list:[]
    }
  },
  created() {
    this.getList()
    this.getReceiptCompanyList()
    this.getOwnershipCompanyList()
    this.getOwnerList()
    this.getSupplyList()
  },
  methods:{
    getSupplyList(){
      let params = {is_page:0};
      if (this.form_data.roleType == 2){
        params = {
          cargoOwnerId:this.form_data.tradeUserId,is_page:0
        }
      }
      supplyList(params).then(res=>{
        this.supply_list = res.rows;
      })
    },
    querySaleList(){
      this.getSaleList()
    },
    resetSaleList(){
      this.sale_list_params = {
        ...this.sale_list_params,
        saleListNumber:'',
      }
      this.getSaleList()
    },
    getSaleList(){
      let sale_list_params = {
        ...this.sale_list_params,
        cargoOwnerId:this.form_data.cargoOwnerId,is_page:0
      }
      saleList(sale_list_params).then(res => {
        this.sale_list = res.rows
      })
    },
    getOwnerList(){
      ownerList({is_page:0}).then(res => {
        this.owner_list = res.rows
      })
    },
    getOwnershipCompanyList(){
      ownershipCompanyList({is_page:0}).then(res => {
        this.ownership_company_list = res.rows
      })
    },
    getReceiptCompanyList(){
      receiptCompanyList({is_page:0}).then(res => {
        this.receipt_company_list = res.rows
      })
    },
    getList(){
      list(this.list_params).then(res => {
        this.list_data = res.rows;
      })
    },
    handleQuery(){
      this.getList()
    },
    resetQuery(){
      this.list_params = {
        pageNum: 1,
        pageSize: 10,
        roleType:'',
        ownershipCompanyId: '',
        oddNumber:''
      }
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delFee(row){
      this.fees.splice(row,1)
    },
    addFee(row){
      this.fees.push({ remark:'' })
    },
    submitData(){
      console.log(this.form_data)
      console.log(this.fees)

      this.$refs.form.validate((valid)=>{
        if (valid){

          let fees = this.fees.map(item => {
            return {
              ...item,
              receiptBelong:4
            }
          })
          let params = {
            ...this.form_data,
            applyUserId:store.getters.user_id,
            applyDate:new Date(),
            xnfReceiptSettleAccountsList:fees
          }
          if (this.form_data.id != undefined){
            update(params).then(res => {
              this.$message.success('编辑成功')
              this.dialog_show = false
              this.getList()
              this.$refs.form.resetFields()
            })
          }else{
            add(params).then(res => {
              this.$message.success('提交成功')
              this.dialog_show = false
              this.$refs.form.resetFields()
              this.getList()
            })
          }

        }
      })

    },
    showInfo(info){
      this.info = {}
      this.supply_order_info = {}
      this.fees = []
      detail(info.id).then(res=>{
        this.info = res.data

      })
      this.edit_dialog_show = true
    },
    editInfo(){
      this.onPaymentRoleChange(this.info.roleType,1)
      this.form_data = {
        ...this.info,
        roleType:this.info.roleType+'',
      }
      let fees = this.info.xnfReceiptSettleAccountsList;
      fees.forEach(item => {
        item.accountId = item.accountId+''
      })
      this.fees = fees
      this.getSupplyList()
      this.edit_dialog_show = false
      this.dialog_show = true
    },
    delitem(row) {
      let id = row.id;
      del(id).then(res=>{
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.getList()
      })
    },
    addInfo(){
      this.form_data = {}
      this.dialog_show = true
      this.fees = [{ remark:'' }]
    },
    onPaymentRoleChange(e,is_eidt = 0){
      if (e == 5){
        capitalList({is_page:0}).then(res=>{
          this.payment_roles = res.rows
        })
      }else{
        customerList({is_page:0}).then(res=>{
          this.payment_roles = res.rows
        })
      }
      if (is_eidt == 0){
        this.form_data = {
          ...this.form_data,
          tradeUserId:''
        }
      }
    },
    onSearchPaymentRoleChange(e){
      if (e == 5){
        capitalList({is_page:0}).then(res=>{
          this.search_payment_roles = res.rows
        })
      }else{
        customerList({is_page:0}).then(res=>{
          this.search_payment_roles = res.rows
        })
      }
    },
    chooseOrder(){
      if (this.form_data.cargoOwnerId == '' || this.form_data.cargoOwnerId== undefined){
        console.log('请选择货主')
        this.$message.error('请选择货主')
        return
      }
      this.order_dialog_show = true
      this.getSaleList()
    },
    orderSelectionChange(selection){
      this.sale_id_list = selection.map(item => item.id);
      this.choose_order_list = selection.map(item => item);
      console.log(this.choose_order_list)
    },
    confirmChoose(){
      let orders = this.choose_order_list
      this.orders = orders;
      this.order_dialog_show = false
    },
    sumData(){
      console.log(this.fees)
      let sum = 0
      this.fees.forEach(item => {
        sum += parseFloat(item.amt)
      })
      this.form_data = {
        ...this.form_data,
        totalPaymentAmt:sum
      }
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]));
        if (index === 0) {
          sums[index] = '合计';
          return;
        } else if (index === 2){
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
      });

      return sums;
    }
  }
}
</script>


<style scoped>
.section{
  background: #fff;
  padding: 24px;
//padding-bottom: 6px;
  margin: 20px;
  border-radius: 8px;
}
.section-item{
  margin: 10px 0px;
  height: 52px;
}
.section-item-title{
  padding-bottom: 10px;
  font-size: 14px;
}
</style>

<style>

.el-drawer__body{
  background: #F3F4F6;
}
.select-custom-icon .el-input__suffix {
  display: none; /* 隐藏默认的下拉箭头 */
}
.select-custom-icon .el-input__suffix::after {
  content: url('../../../assets/icons/more.png'); /* 替换为您的自定义图标路径 */
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}
.popper-class{
  display: none;
}

</style>
